<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use \Think\Log;

/**
 * 模型数据管理控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class AdvertiseContentController extends AdminController {
    
    /**
     * 显示指定模型列表数据
     * @param  String $model 模型标识
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function lists($model = 'advertise_content', $p = 0)
    {
        $model || $this->error('模型名标识必须！');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        
        //获取模型信息
        $model = M('Model')->getByName($model);
       
        $model || $this->error('模型不存在！');

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
        	if(trim($value) === ''){
        		continue;
        	}
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array	=	explode('|',$val);
                $fields[] = $array[0];
            }
        }
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        $map	=	array();
        $key	=	$model['search_key']?$model['search_key']:'title';
        if(isset($_REQUEST[$key])){
            $map[$key]	=	array('like','%'.$_GET[$key].'%');
            unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach($_REQUEST as $name=>$val){
            if(in_array($name,$fields)){
                //$map[$name]	=	$val;
            }
        }
        $row = empty($model['list_row']) ? 15 : $model['list_row'];
        
        if (!isset($map['status'])) {
            $map['status'] = 1;
        }
        $category_id=$_REQUEST['id'];
        $map['category_id']=$_REQUEST['id'];
        //读取模型数据列表
        if($model['extend']){
            $name   = get_table_name($model['id']);
            $parent = get_table_name($model['extend']);
            $fix    = C("DB_PREFIX");

            $key = array_search('id', $fields);
            if(false === $key){
                array_push($fields, "{$fix}{$parent}.id as id");
            } else {
                $fields[$key] = "{$fix}{$parent}.id as id";
            }

            /* 查询记录数 */
            $count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
            $data   = M($parent)
                ->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order("{$fix}{$parent}.id DESC")
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

        } else {
            if($model['need_pk']){
                in_array('id', $fields) || array_push($fields, 'id');
            }
            $name = parse_name(get_table_name($model['id']), true);
          
            $data = M($name,'cms_')
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order($model['need_pk']?'id DESC':'')
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();
           
            /* 查询记录总数 */
            $count = M($name,'cms_')->where($map)->count();
        }

        foreach ($data as $k=>$v){
            $data[$k]['show']=($v['show']==1?"多广告展示":"单广告展示");
            $data[$k]['type']=($v['type']==1?"启用":"不启用");
           
        }
   
        
        //分页
        if($count > $row){
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }
        $data   =   $this->parseDocumentList($data,$model['id']);
      
        $this->assign('category_id',$category_id);
        $this->assign('_count', $count);
        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->meta_title = $model['title'].'列表';
        $this->display($model['template_list']);
    }

    public function del($model = 'advertise_content', $ids=null){
       
       

        $ids = array_unique((array)I('ids',0));

        if ( empty($ids) ) {
            $this->error('请选择要操作的数据!');
        }

        //$Model = M(get_table_name($model['id']));
        $Model=M('AdvertiseContent','cms_');
        $map['category_id']=$_REQUEST['category_id'];
        $adcon=$Model->where($map)->select();
        //判断当前的数量是否小于5，小于5,不允许删除
        if(count($adcon)<=5){
           $this->error('底部导航数量不允许小于5,不允许删除');
        }
        $map = array('id' => array('in', $ids) );
        if($Model->where($map)->delete()){
            $this->success('删除成功');
        } else {
            $this->error('删除失败！');
        }
    }

    /**
     * 设置一条或者多条数据的状态
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus($model='Document'){
        return parent::setStatus($model);
    }
    
    public function edit($model = 'advertise_content', $id = 0){
        //获取模型信息
        $model = M('Model')->find($model);
        //$model || $this->error('模型不存在！');

       
        if(IS_POST){
            //var_dump($_POST);exit;
            $_POST['start_time']=strtotime($_POST['start_time']);
            $_POST['end_time']=strtotime($_POST['end_time']);
            if($_POST['start_time']>$_POST['end_time']){
                $this->error('开始时间大于结束时间');
            }
            $Model= M('advertise_content','cms_');
            //判断是否是顺序3是不是商城
            $threeInfo=M('AdvertiseContent','cms_')->where(array('order'=>3))->find();
            if($_POST['category_id']==59 && $threeInfo['id'] && $threeInfo['id']==$_POST['id']){
                if($threeInfo['title']!=$_POST['title'] || $threeInfo['order']!=$_POST['order']){
                    $this->error('顺序3的标题和顺序不允许修改');
                }
            }
            $Model=M('AdvertiseContent','cms_');
            $threeInfo=$Model->where(array('order'=>$_POST['order'],'category_id'=>$_POST['category_id']))->find();
            
            if($_POST['category_id']==59 && $threeInfo && $threeInfo['id']!=$id){ 
                
                $this->error('该顺序已经存在，不允许在添加,请修改后添加');
            }
            //查询出position值
            
            $_POST['position']=M('advertise_position_map','cms_')->where(array('category_id'=>$_POST['category_id']))->getField('position_id');
            
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && ($Model->save()!==false)){
                //更新广告表的添加时间
                $advertiseData['addtime']=time();
                //将图片同步到img.wttai.com下               
                $res = $this->sendImg($_POST['en_img'],1);
                $res2 = $this->sendImg($_POST['ch_img'],1);               
                if($res['code'] == 0 && $res2['code'] == 0){
                    M('Advertise','cms_')->where(array('id'=>$_POST['category_id']))->save($advertiseData);
                    $this->success('保存'.$model['title'].'成功！', U('lists?model='.$model['name'],array('id'=>$_POST['category_id'])));
                }else{
                    Log::record('广告图片转存en', $res['desc']);
                    Log::record('广告图片转存ch', $res2['desc']);
                    $this->error('图片有误，请稍后重试');
                }
            } else {
                $this->error($Model->getError());
            }
        } else {
            //获取数据
            $fields     = get_model_attribute($model['id'],true,$field);
           // dump($fields);exit;
            $data       = M('advertise_content','cms_')->field()->find($id);
            $advertise=M('Advertise','cms_')->select(array('index'=>'id'));
            $this->assign('advertise',$advertise);
            $data || $this->error('数据不存在！');
            $this->assign('model', $model);
            $this->assign('fieldNum',$fieldNum);
            $this->assign('fields', $fields);
            $this->assign('data', $data);
            $this->meta_title = '编辑'.$model['title'];
            $this->display($model['template_edit']?$model['template_edit']:'');
        }
    }

    public function add($model = null){
        //获取模型信息
        $model = M('Model')->where(array('status' => 1))->find($model);
        $model || $this->error('模型不存在！');
        if(IS_POST){
            $_POST['position']=$_POST['category_id'];
            /* if(!$_POST['title'] || !$_POST['ch_img'] || !$_POST['en_img'] || !$_POST['url']){
                $this->error('标题，未点击图片，点击按钮图片，链接不能为空，请重新填写');
            } */ 
            $start_time=strtotime($_POST['start_time']);
            $end_time=strtotime($_POST['end_time']);
            if($start_time>$end_time){
                $this->error('开始时间大于结束时间');
            }
            $Model=M('AdvertiseContent','cms_');
            $threeInfo=$Model->where(array('order'=>$_POST['order'],'category_id'=>$_POST['category_id']))->find();
            if($threeInfo){
                 $this->error('该顺序已经存在，不允许在添加,请修改后添加');
            }
            
            $_POST['position']=M('advertise_position_map','cms_')->where(array('category_id'=>$_POST['category_id']))->getField('position_id');//查出position值
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            //dump($_POST);exit;
            if($Model->create() && $Model->add()){
                $advertiseData['addtime']=time();
                //将图片同步到img.wttai.com下
                $res = $this->sendImg($_POST['en_img']);
                $res2 = $this->sendImg($_POST['ch_img']);
                if($res['code']==0 && $res2['code']==0){
                    M('Advertise','cms_')->where(array('id'=>$_POST['category_id']))->save($advertiseData);
                    $this->success('添加'.$model['title'].'成功！', U('lists?model='.$model['name'],array('id'=>$_POST['category_id'])));
                }else{
                    Log::record('广告图片转存en', $res['desc']);
                    Log::record('广告图片转存ch', $res2['desc']);
                    $this->error('图片有误，请稍后重试');
                }
                
            } else {
                $this->error($Model->getError());
            }
        } else {
            //获取
            $fields = get_model_attribute($model['id']);
            $categoryId=$_REQUEST['category_id'];
            //获取到广告位置值
            $advertise=M('Advertise','cms_')->select(array('index'=>'id'));
            $this->assign('advertise',$advertise);
            $this->assign('categoryId',$categoryId);
            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->meta_title = '新增'.$model['title'];
            $this->display($model['template_add']?$model['template_add']:'');
        }
    }
    protected function sendImg($path,$v=0){
        if(!$path)return array('code'=>0); 

        if($v==1){          
            $sic=show_img_complete($path,1);           
            if($sic==2){
                return array('code'=>0); 
            }elseif($sic==1){
                $urlImg="http://api.wttai.com/inner/upload";
                $data['path']=$path;            
                $img =file_get_contents($path);            
                $data['img']=base64_encode($img);
                $res=curl_post($urlImg,$data);
                $res=json_decode($res,true);
                return $res; 
            }else{
                return array('code'=>0); 
            }          
            
        }else{          
            $urlImg="http://api.wttai.com/inner/upload";
            $data['path']=$path;
            $localPath = PUBPATH.str_replace('/', DIRECTORY_SEPARATOR, $data['path']);
            $localPath = str_replace('\\\\', '\\', $localPath);            
            $img =file_get_contents($localPath);
            $data['img']=base64_encode($img);
            $res=curl_post($urlImg,$data);
            $res=json_decode($res,true);
            return $res; 
        }
        
    }
    
    
    protected function checkAttr($Model,$model_id){
        $fields     =   get_model_attribute($model_id,false);
        $validate   =   $auto   =   array();
        foreach($fields as $key=>$attr){
            if($attr['is_must']){// 必填字段
                $validate[]  =  array($attr['name'],'require',$attr['title'].'必须!');
            }
            // 自动验证规则
            if(!empty($attr['validate_rule'])) {
                $validate[]  =  array($attr['name'],$attr['validate_rule'],$attr['error_info']?$attr['error_info']:$attr['title'].'验证错误',0,$attr['validate_type'],$attr['validate_time']);
            }
            // 自动完成规则
            if(!empty($attr['auto_rule'])) {
                $auto[]  =  array($attr['name'],$attr['auto_rule'],$attr['auto_time'],$attr['auto_type']);
            }elseif('checkbox'==$attr['type']){ // 多选型
                $auto[] =   array($attr['name'],'arr2str',3,'function');
            }elseif('date' == $attr['type']){ // 日期型
                $auto[] =   array($attr['name'],'strtotime',3,'function');
            }elseif('datetime' == $attr['type']){ // 时间型
                $auto[] =   array($attr['name'],'strtotime',3,'function');
            }
        }
        return $Model->validate($validate)->auto($auto);
    } 
    
}